package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.order.order.entity.dos.*;
import cn.lili.modules.order.order.entity.dos.RankingGrowAwardConfig;
import cn.lili.modules.order.order.entity.dos.RankingGrowAwardStatus;
import cn.lili.modules.order.order.entity.vo.GrowthRewardVO;
import cn.lili.modules.order.order.entity.vo.ViewLogisticVO;
import cn.lili.modules.order.order.mapper.RankingGrowAwardConfigMapper;
import cn.lili.modules.order.order.service.IRankingAwardDetailsService;
import cn.lili.modules.order.order.service.IRankingDistributionService;
import cn.lili.modules.order.order.service.IRankingGrowAwardConfigService;
import cn.lili.modules.order.order.service.IRankingGrowAwardStatusService;
import cn.lili.modules.system.client.LogisticsClient;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.modules.system.entity.vo.Traces;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 成长奖励奖品配置 服务实现类
 * </p>
 *
 * @author zhushiqing
 * @since 2023-12-21
 */
@Service
@AllArgsConstructor(onConstructor_= @Lazy)
public class RankingGrowAwardConfigServiceImpl extends ServiceImpl<RankingGrowAwardConfigMapper, RankingGrowAwardConfig> implements IRankingGrowAwardConfigService {

    private IRankingGrowAwardStatusService rankingGrowAwardStatusService;

    private LogisticsClient logisticsClient;

    private IRankingAwardDetailsService awardDetailsService;
    private IRankingDistributionService distributionService;
    /**
     * 成长奖励: 获取当前用户佣金值，与当前活动的奖品与佣金（需返回是否领取过）
     *
     * @return 成长奖励
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public GrowthRewardVO growthReward() {
        GrowthRewardVO result = new GrowthRewardVO();
        //当前用户的总佣金
        result.setCurrentCommission(BigDecimal.valueOf(0));
        result.setMaxCommission(BigDecimal.valueOf(0));
        RankingDistribution distribution = distributionService.getRankingDistribution();
        if (distribution != null && distribution.getRebateTotal() != null) {
            result.setCurrentCommission(distribution.getRebateTotal());
        }
        //奖品集合
        this.addConfig(result, distribution);
        return result;
    }


    /**
     * 领取奖励 (需判断是否领取过   是否达到了领奖条件)
     *
     * @param rankingGrowAwardStatus 奖品id,收货信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<Object> receiveAReward(RankingGrowAwardStatus rankingGrowAwardStatus) {
        if (StringUtils.isEmpty(rankingGrowAwardStatus.getGrowAwardConfigId())) {
            throw new ServiceException("领取的奖品id为空：growAwardConfigId");
        }
        RankingGrowAwardConfig growAwardConfig = super.getById(rankingGrowAwardStatus.getGrowAwardConfigId());
        RankingDistribution distribution = distributionService.getRankingDistribution();
        //校验
        this.check(growAwardConfig, distribution, rankingGrowAwardStatus);

        //领取奖励
        LambdaQueryWrapper<RankingGrowAwardStatus> growAwardStatusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        growAwardStatusLambdaQueryWrapper.eq(RankingGrowAwardStatus::getGrowAwardConfigId, rankingGrowAwardStatus.getGrowAwardConfigId());
        growAwardStatusLambdaQueryWrapper.eq(RankingGrowAwardStatus::getDistributionId, distribution.getId());
        growAwardStatusLambdaQueryWrapper.eq(RankingGrowAwardStatus::getAwardStatus, DictConstant.AWARD_STATUS_0);
        RankingGrowAwardStatus growAwardStatus = rankingGrowAwardStatusService.getOne(growAwardStatusLambdaQueryWrapper);
        if (growAwardStatus == null) {
            growAwardStatus = new RankingGrowAwardStatus();
            rankingGrowAwardStatus.setAwardStatus(DictConstant.AWARD_STATUS_0);
            rankingGrowAwardStatus.setDistributionId(distribution.getId());
            rankingGrowAwardStatus.setGrowAwardConfigId(rankingGrowAwardStatus.getGrowAwardConfigId());
            rankingGrowAwardStatusService.save(growAwardStatus);
//            throw new ServiceException("未获取到待领奖信息");
        }

        rankingGrowAwardStatus.setAwardStatus(DictConstant.AWARD_STATUS_1);
        rankingGrowAwardStatus.setDistributionId(distribution.getId());
        rankingGrowAwardStatus.setId(growAwardStatus.getId());
        rankingGrowAwardStatusService.updateById(rankingGrowAwardStatus);

        return ResultUtil.success();
    }

    /**
     * 查看物流
     *
     * @param claimableId 领取信息id
     * @return 收货信息 + 物流信息
     */
    @Override
    public ResultMessage<Object> viewLogistic(String claimableId) {
        ViewLogisticVO result = new ViewLogisticVO();
        //收货信息
        RankingGrowAwardStatus growAwardStatus = rankingGrowAwardStatusService.getById(claimableId);
        if (growAwardStatus == null) {
            growAwardStatus = this.getGrowAwardDetail(claimableId);
            if (growAwardStatus == null) {
                throw new ServiceException("未获取到领用信息");
            }
        }
        result.setGrowAwardStatus(growAwardStatus);
        result.setTraces(new Traces());
        //物流信息
        if (StringUtils.isNotEmpty(growAwardStatus.getExpressNo()) && StringUtils.isNotEmpty(growAwardStatus.getExpressName())) {
            //手机号后四位
            String phone = growAwardStatus.getDeliveryPhone().substring(growAwardStatus.getDeliveryPhone().length() - 4);
            Traces logistic = logisticsClient.getLogistic(growAwardStatus.getExpressName(), growAwardStatus.getExpressNo(), phone);
            result.setTraces(logistic);
        }
        return ResultUtil.data(result);
    }

    /**
     * 查询排名，领奖信息物流
     */
    public RankingGrowAwardStatus getGrowAwardDetail(String id) {
        RankingAwardDetails awardDetails = awardDetailsService.getById(id);
        if (awardDetails != null) {
            RankingGrowAwardStatus growAwardStatus = new RankingGrowAwardStatus();
            BeanUtils.copyProperties(awardDetails, growAwardStatus);
            return growAwardStatus;
        }
        return null;
    }

    /**
     * 奖品集合
     *
     * @param result       返回结果
     * @param distribution 店主
     */
    private void addConfig(GrowthRewardVO result, RankingDistribution distribution) {
        LambdaQueryWrapper<RankingGrowAwardConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RankingGrowAwardConfig::getDeleteFlag, Boolean.FALSE);
        List<RankingGrowAwardConfig> configList = super.list(queryWrapper);
        if (CollectionUtil.isEmpty(configList)) {
            return;
        }
        for (RankingGrowAwardConfig rankingGrowAwardConfig : configList) {
            rankingGrowAwardConfig.setIsGet(false);
            rankingGrowAwardConfig.setIsClaimable(false);
            //commissCondition为空数据不正常  || 不是店主不能领奖
            if (rankingGrowAwardConfig.getCommissCondition() == null || distribution == null) {
                continue;
            }
            //达到可领取奖励的条件
            if (result.getCurrentCommission().doubleValue() >= rankingGrowAwardConfig.getCommissCondition().doubleValue()) {
                rankingGrowAwardConfig.setIsClaimable(true);
                //是否已经领取
                LambdaQueryWrapper<RankingGrowAwardStatus> growAwardStatusLambdaQueryWrapper = new LambdaQueryWrapper<>();
                growAwardStatusLambdaQueryWrapper.eq(RankingGrowAwardStatus::getDistributionId, distribution.getId());
                growAwardStatusLambdaQueryWrapper.eq(RankingGrowAwardStatus::getGrowAwardConfigId, rankingGrowAwardConfig.getId());
                growAwardStatusLambdaQueryWrapper.orderByDesc(RankingGrowAwardStatus::getCreateTime);
                growAwardStatusLambdaQueryWrapper.last("limit 1");
                RankingGrowAwardStatus growAwardStatus = rankingGrowAwardStatusService.getOne(growAwardStatusLambdaQueryWrapper);
                //有值，且不为未领取 ==  已领取
                if (growAwardStatus != null && !DictConstant.AWARD_STATUS_0.equals(growAwardStatus.getAwardStatus())) {
                    rankingGrowAwardConfig.setIsGet(true);
                    //获取领用信息 =》 物流单号 =》 查询物流信息
                    rankingGrowAwardConfig.setClaimableId(growAwardStatus.getId());
                }
                //达到了可领奖条件，但还未生成待领取记录  ==》 生成待领取记录
                if (growAwardStatus == null) {
                    RankingGrowAwardStatus rankingGrowAwardStatus = new RankingGrowAwardStatus();
                    rankingGrowAwardStatus.setAwardStatus(DictConstant.AWARD_STATUS_0);
                    rankingGrowAwardStatus.setDistributionId(distribution.getId());
                    rankingGrowAwardStatus.setGrowAwardConfigId(rankingGrowAwardConfig.getId());
                    rankingGrowAwardStatusService.save(rankingGrowAwardStatus);
                }
            }
        }
        result.setGrowAwardConfigList(configList);
        Optional<RankingGrowAwardConfig> configOptional = configList.stream().max(Comparator.comparing(RankingGrowAwardConfig::getCommissCondition));
        if (configOptional.isPresent()) {
            BigDecimal commissCondition = configOptional.get().getCommissCondition();
            result.setMaxCommission(commissCondition);
        }
    }

    /**
     * 校验
     */
    private void check(RankingGrowAwardConfig growAwardConfig, RankingDistribution distribution, RankingGrowAwardStatus rankingGrowAwardStatus) {
        if (StringUtils.isEmpty(rankingGrowAwardStatus.getDeliveryName())) {
            throw new ServiceException("收货人为空：deliveryName");
        }
        if (StringUtils.isEmpty(rankingGrowAwardStatus.getDeliveryPhone())) {
            throw new ServiceException("收货人手机号为空：deliveryPhone");
        }
        if (StringUtils.isEmpty(rankingGrowAwardStatus.getDeliveryAddress())) {
            throw new ServiceException("收货地址为空：deliveryAddress");
        }
        if (growAwardConfig == null) {
            throw new ServiceException("未获取到奖品信息");
        }
        if (distribution == null) {
            throw new ServiceException("不是店主，请先申请店主");
        }
        if (distribution.getRebateTotal() == null || distribution.getRebateTotal().doubleValue() < growAwardConfig.getCommissCondition().doubleValue()) {
            throw new ServiceException("未到达领取条件,请继续努力");
        }

    }


    /**
     * 添加成长奖励配置
     *
     * @param config
     * @return
     */
    @Override
    public ResultMessage addRankingGrowAwardConfig(RankingGrowAwardConfig config) {
        //添加成长奖励参数检查
        this.checkParam(config);
        if (baseMapper.insert(config) > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }

    /**
     * 成长奖励参数检查
     * @param config
     */
    private void checkParam(RankingGrowAwardConfig config) {
        if (StringUtils.isEmpty(config.getGrowAwardName())) {
            throw new ServiceException("奖品名称不可为空");
        }
        if (StringUtils.isEmpty(config.getGrowAwardImg())) {
            throw new ServiceException("奖品图片不可为空");
        }
        if (null == config.getCommissCondition() || config.getCommissCondition().compareTo(BigDecimal.ZERO) == 0) {
            throw new ServiceException("佣金条件不可为0");
        }
    }


    /**
     * 编辑成长奖励奖品
     * @param config
     * @return
     */
    @Override
    public ResultMessage editRankingGrowAwardConfig(RankingGrowAwardConfig config) {
        if (null == config || null == config.getId()) {
            return ResultUtil.error(400, "成长奖励奖品ID不可为空");
        }
        RankingGrowAwardConfig configData = baseMapper.selectById(config.getId());
        if (null == configData || configData.getDeleteFlag()) {
            return ResultUtil.error(400, "未找到该成长奖励奖品");
        }
        if (baseMapper.updateById(config) > 0) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(400, "修改失败");
        }
    }

    /**
     * 删除成长奖励奖品
     * @param id
     * @return
     */
    @Override
    public ResultMessage deleteRankingGrowAwardConfig(String id) {
        RankingGrowAwardConfig configData = baseMapper.selectById(id);
        if (null == configData || configData.getDeleteFlag()) {
            return ResultUtil.error(400, "未找到该成长奖励奖品");
        }
        UpdateWrapper<RankingGrowAwardConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("delete_flag", Boolean.TRUE);
        if (this.update(updateWrapper)) {
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }

    /**
     * 获取成长奖励配置
     *
     * @return
     */
    @Override
    public List<RankingGrowAwardConfig> getRankingGrowAwardConfigs() {
        LambdaQueryWrapper<RankingGrowAwardConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RankingGrowAwardConfig::getDeleteFlag, Boolean.FALSE);
        List<RankingGrowAwardConfig> awardConfigs = baseMapper.selectList(queryWrapper);
        return awardConfigs;
    }


    @Override
    public ResultMessage getRankingGrowAwardConfigListKeyVal() {
        LambdaQueryWrapper<RankingGrowAwardConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RankingGrowAwardConfig::getDeleteFlag, Boolean.FALSE);
        queryWrapper.select(RankingGrowAwardConfig::getId, RankingGrowAwardConfig::getGrowAwardName);
        List<RankingGrowAwardConfig> awardConfigs = baseMapper.selectList(queryWrapper);
        return ResultUtil.data(awardConfigs);
    }
}
